package org.study.plus.boot.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.study.plus.boot.mapper.ReportInstanceMapper;
import org.study.plus.boot.mapper.ReportTemplateMapper;
import org.study.plus.boot.model.ReportInstance;
import org.study.plus.boot.model.ReportTemplate;
import org.study.plus.boot.vo.ReportInstanceDTO;

import java.time.LocalDateTime;

/**
 * 报表实例信息
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2025年08月19日
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Service
public class ReportInstanceServiceImpl extends ServiceImpl<ReportInstanceMapper, ReportInstance> implements ReportInstanceService {
    private final ReportTemplateMapper reportTemplateMapper;

    @Override
    public boolean addReportInstance(ReportInstanceDTO reportInstanceDTO) {
        ReportTemplate reportTemplate = reportTemplateMapper.selectById(reportInstanceDTO.getTemplateId());
        if (reportTemplate == null) {
            throw new RuntimeException("报表模板不存在");
        }
        // 新增
        ReportInstance reportInstance = new ReportInstance();
        BeanUtils.copyProperties(reportInstanceDTO, reportInstance);
        // reportInstance.setId(null);
        // 如果报表实例的内容为空，就暂时使用模板中的内容
        if (StringUtils.isBlank(reportInstanceDTO.getName())) {
            reportInstance.setName(reportTemplate.getTemplateName() + "_报表_" + System.currentTimeMillis());
        }
        // 如果报表实例的内容为空，就暂时使用模板中的内容
        if (StringUtils.isBlank(reportInstanceDTO.getContent())) {
            reportInstance.setContent(reportTemplate.getTemplateContent());
        }
        reportInstance.setTemplateId(reportTemplate.getId());
        reportInstance.setTemplateVersion(reportTemplate.getTemplateVersion());
        reportInstance.setIsDeleted(0);
        reportInstance.setCreateUserId(0L);
        reportInstance.setCreateUserName("test");
        reportInstance.setCreateTime(LocalDateTime.now());
        baseMapper.insert(reportInstance);
        return true;
    }

    @Override
    public boolean updateReportInstance(ReportInstanceDTO reportInstanceDTO) {
        // 新增
        ReportInstance reportInstance = new ReportInstance();
        BeanUtils.copyProperties(reportInstanceDTO, reportInstance);
        reportInstance.setTemplateId(null);
        reportInstance.setTemplateVersion(null);
        reportInstance.setUpdateUserId(0L);
        reportInstance.setUpdateUserName("test");
        reportInstance.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(reportInstance);
        return true;
    }
}
